from __future__ import print_function
import os
from wmi import WMI
import json
from function.Log import Log, INFO, WARNNING, CMD, ERROR
from colorama import Fore, Back, Style

class EthSwitch:
    """以太网设置切换
    """
    def __init__(self):
        self.wmi_service = WMI()
        self.interface_name = "00:50:56:C0:00:08"
        self.configs = self.wmi_service.Win32_NetworkAdapterConfiguration(IPEnabled=True)
        self.suojin = "        "


    def get_interface_active(self) -> int:
        """获取活跃状态的网卡

        Returns:
            int: 返回寻找到的网卡
        """
        for interface_id in range(len(self.configs)):
            # print(interface.IPAddress[0])
            # print(self.configs[interface_id].MACAddress)
            if self.configs[interface_id].MACAddress == self.interface_name:
                # print("id: {}".format(interface_id))
                return interface_id
        return -1


    def run_manual(self) -> None:
        """手动配置IP
        """
        interface_id = self.get_interface_active()
        
        if interface_id == -1:
            Log(True, "r", "请检查网卡MAC地址是否配置正确，找不到此网卡！")
        
        interface = self.configs[interface_id]
        # print(_wmi_objec._getAttribute_())
        print("\n\n{}******************** 网卡详细信息 *********************\n".format(Fore.RED))
        Log(True, "yw", "IPADDRESS: {}\nMACADDRESS: {}".format(interface.IPAddress, interface.MACAddress))

        # 修改静态IP
        print("\n\n*********************** 开始手动修改IP ***********************\n")
        ip = input(">>>>> 输入IP：")
        subnetMask = input(">>>>> 输入子网掩码：")
        
        try:
            ipres = interface.EnableStatic(IPAddress=[ip], SubnetMask=[subnetMask])
            Log(False, "yw", ipres)
        except Exception as e:
            Log(True, "r", "\n#################异常：{}".format(e))
            os.system("pause")
        else:
            if ipres[0] == 0:
                Log(True, "gn", "^^^^^^^^^^^^^^^IP设置成功！！！")
            else:
                Log(True, "r", "^^^^^^^^^^^^^^^IP设置失败！！！")


    def run_auto(self) -> None:
        """自动配置IP
        """
        interface_dict = {}
        print("\n{} 当前所有网卡IP设置状态:\n\n".format(INFO))
        for interface_id in range(len(self.configs)):
            interface_dict[interface_id] = self.configs[interface_id]
            Log(True, "wh", "{}[{}] {}=======>{} Interface: {}\n"
                "             ip: {}\n             NetMask: {}".format(self.suojin,
                                                                        Fore.CYAN + str(interface_id) + Fore.RESET,
                                                                        Fore.BLUE, Fore.RESET,
                                                                        Fore.YELLOW + self.configs[interface_id].Description + Fore.RESET,
                                                                        Fore.YELLOW + self.configs[interface_id].IPAddress[0] + Fore.RESET,
                                                                        Fore.YELLOW + self.configs[interface_id].IPSubnet[0] + Fore.RESET))
        
        option = int(input("\n请选择需要配置IPDRESS的网卡: "))
        while option >= len(interface_dict):
            Log(True, "r", "\n{} 网卡序号错误，请填写上方列出的网卡序号!!".format(ERROR))
            option = int(input("\n请选择需要配置IPDRESS的网卡: "))
        
        print("\n\n{}======================================== 根据提示修改IP =======================================\n".format(Fore.RED))
        
        print("{} 正在加载常用IP地址.......\n".format(INFO))

        often_use_address_list = self.load_often_use_ipaddress()
        for addr_id in range(len(often_use_address_list)):
            Log(True, "wh", "{}[{}] {}=======>{} ip: {} netmask: {}".format(self.suojin,
                                                                         Fore.CYAN + str(addr_id) + Fore.RESET,
                                                                         Fore.BLUE, Fore.RESET,
                                                                        Fore.YELLOW + often_use_address_list[addr_id]["ip"] + Fore.RESET,
                                                                        Fore.YELLOW + often_use_address_list[addr_id]["ipsubnet"] + Fore.RESET))
        
        print("{}===============================================================================================".format(Fore.RED))

        ip_option = int(input("\n\n 将IP地址替换为序号 >>>>>>>>> "))
        while ip_option >= len(often_use_address_list):
            Log(True, "r", "{} 地址序号错误，请填写上方列出的地址序号!!!".format(INFO))
            ip_option = int(input("设置IP地址为序号 >>>>>>>>> "))
        
        # print(interface_dict[option])
        Log(True, "wh", "\n\n{} 正尝试将地址 [{} && {}] 更改为 [{} && {}]\n".format(INFO, Fore.YELLOW + interface_dict[option].IPAddress[0] + Fore.RESET, 
                                                  Fore.YELLOW + interface_dict[option].IPSubnet[0] + Fore.RESET,
                                                  Fore.CYAN + often_use_address_list[ip_option]["ip"] + Fore.RESET,
                                                  Fore.CYAN + often_use_address_list[addr_id]["ipsubnet"] + Fore.RESET))

        try:
            ipres = interface_dict[option].EnableStatic(IPAddress=[often_use_address_list[ip_option]["ip"]],
                                                        SubnetMask=[often_use_address_list[ip_option]["ipsubnet"]])
            # print(ipres)
        except Exception as e:
            Log(True, "r", "\n{} 异常：{}".format(ERROR, e))
            os.system("pause")
        else:
            if ipres[0] == 0:
                Log(True, "gn", "{} 结果： IP设置成功".format(INFO))
            else:
                Log(True, "r", "{} 结果： IP设置失败".format(WARNNING))


    def load_often_use_ipaddress(self) -> list:
        try:
            with open("ipaddress.json", "r") as f:
                data = json.load(f)
            return data["address"]
        except Exception as e:
            Log(True, "r", "\n加载常用IP地址异常：{}".format(e))
            os.system("pause")

    
    def run_DHCP(self) -> None:
        """切换DHCP
        """
        # 自动获取DNS
        interface_dict = {}
        print("当前所有网卡IP设置状态:\n\n")
        for interface_id in range(len(self.configs)):
            interface_dict[interface_id] = self.configs[interface_id]
            Log(True, "wh", "{}[{}] {}=======>{} Interface: {}\n"
                "             ip: {}\n             NetMask: {}".format(self.suojin,
                                                                        Fore.CYAN + str(interface_id) + Fore.RESET,
                                                                        Fore.BLUE, Fore.RESET,
                                                                        Fore.YELLOW + self.configs[interface_id].Description + Fore.RESET,
                                                                        Fore.YELLOW + self.configs[interface_id].IPAddress[0] + Fore.RESET,
                                                                        Fore.YELLOW + self.configs[interface_id].IPSubnet[0] + Fore.RESET))
        
        option = int(input("\n请选择需要配置IPDRESS的网卡: "))
        while option >= len(interface_dict):
            Log(True, "r", "\n{} 网卡序号错误，请填写上方列出的网卡序号!!".format(ERROR))
            option = int(input("\n请选择需要配置IPDRESS的网卡: "))
        
        interface = interface_dict[option]
        try:
            dns_res = interface.SetDNSServerSearchOrder()
            if dns_res[0] == 0 or dns_res[0] == 1:
                Log(True, "gn", "设置自动获取DNS成功！！！")
            else:
                Log(True, "r", "设置自动获取DNS失败！")
        except Exception as e:
            Log(True, "r", "\n异常：{}".format(e))
            os.system("pause")

        try:
            dns_dhcp = interface.EnableDHCP()
            if dns_dhcp[0] == 0 or dns_dhcp[0] == 1:
                Log(True, "gn", "DHCP获取IP成功！！")
            else:
                Log(True, "r", "DHCP获取IP失败！")
        except Exception as e:
            Log(True, "r", "\n异常：{}".format(e))
            os.system("pause")
